import { onMounted, onUnmounted, ref, watch } from "vue";
import { GenNonDuplicateID } from "./other";
import { useCode } from "./writeCode";
import { getLayoutById } from "@renderer/api/layout";

const { ipcRenderer } = window;

// 导出文件
export const exportFile = async (
  name: string,
  layout: any,
  configsJson: any
) => {
  let jsonInfo = JSON.stringify({ name, layout, configsJson });
  const projectPath = await ipcRenderer.invoke("openFileChooseDialog", {
    file: "",
    title: `选择文件夹`,
  });
  console.log("projectPath", projectPath);
  if (projectPath) {
    // 写入页面
    const writeRes = await ipcRenderer.invoke("writeFile", {
      path: `${projectPath}\\${name}.json`,
      data: jsonInfo,
    });
    ElMessage.success(name + "导出成功");
  }
};
function isJsonFile(filename) {
  console.log(filename);
  return filename.name.toLowerCase().endsWith(".json");
}
// 导入文件
export const importFile = async () => {
  const filePath = await ipcRenderer.invoke("openDialog");
  if (isJsonFile(filePath)) {
    const files = await ipcRenderer.invoke("readFile", filePath.path);
    let res = JSON.parse(files);
    // ElMessage.success("文件" + res.name + "导入成功");
    return res;
  } else {
    ElMessage.error("请导入json格式的文件");
    return false;
  }
};

// 将生成的代码文件写入
export const codeToProject = async (
  codeText: any,
  allComponentsArrs: any[]
) => {
  const projectPath = await ipcRenderer.invoke("openFileChooseDialog", {
    file: "",
    title: "选择项目根目录文件夹",
  });
  // 创建jsons文件夹
  let resDir = await ipcRenderer.invoke("makeDir", {
    path: projectPath + "\\" + "src" + "\\" + "jsons",
  });
  // 写入页面
  await ipcRenderer.invoke("writeFile", {
    path: projectPath + "\\" + "src" + "\\" + "views" + "\\" + "DemoView.vue",
    data: codeText,
  });
  // 写入json
  allComponentsArrs.forEach((item) => {
    getJsonPath(
      projectPath + "\\" + "src" + "\\" + "jsons",
      item.componentName + item.id + ".json",
      JSON.stringify(item.props)
    );
  });
  ElMessage.success("代码生成成功！");
};

const getJsonPath = async (filePath, name: string, result) => {
  const writeRes = await ipcRenderer.invoke("writeFile", {
    path: filePath + "\\" + name,
    data: result,
  });
  // ElMessage.success(name + writeRes);
  // ElMessage.success("代码生成成功！");
};

// 生成代码
export const generateCode: any = async (layout: any, configsJson: any) => {
  if (layout.length <= 0) return;
  /* 需要读写的文件地址 */
  const path = ipcRenderer.sendSync("getTemplatePath", "code_vue.txt");
  // console.log(path);
  let res = await ipcRenderer.invoke("readFile", path);

  const {
    importJsonStr,
    importStr,
    htmlStr,
    configsJsonStr,
    requestStr,
    allComponentsArr,
    mountedStr,
    variableStr,
    timer,
    unMountedStr,
  } = useCode(
    layout,
    configsJson //全局属性
  );

  let result = res
    .replace(/<%mountedStr%>/g, mountedStr)
    .replace(/<%importJsonStr%>/g, importJsonStr)
    .replace(/<%requestStr%>/g, requestStr)
    .replace(/<%variableStr%>/g, variableStr)
    .replace(/<%importStr%>/g, importStr)
    .replace(/<%configsJsonStr%>/g, configsJsonStr)
    .replace(/<%timer%>/g, timer)
    .replace(/<%unMountedStr%>/g, unMountedStr)
    .replace(/<%template%>/g, htmlStr);
  let allComponentsArrsList = [];

  if (result) {
    allComponentsArrsList = [...allComponentsArr];
  }
  return {
    result,
    allComponentsArrsList,
  };
};

export const exportStaticData = async (name: string, data: any) => {
  const projectPath = await ipcRenderer.invoke("openFileChooseDialog", {
    file: "",
    title: `选择文件夹`,
  });
  if (projectPath) {
    // 写入页面
    const writeRes = await ipcRenderer.invoke("writeFile", {
      path: `${projectPath}\\${name}.json`,
      data: data,
    });
    ElMessage.success(name + writeRes);
  }
};

// export const useProjectPreview = () => {
//   let flag = ref(false);

//   let currentItem = ref<any>({});
//   const preview = async ({ id }) => {
//     let res = await getLayoutById(id);
//     currentItem.value = res.data;
//     let name = "layout" + GenNonDuplicateID(6);
//     ipcRenderer.invoke("open-win", {
//       url: "/preview?id=" + name,
//     });
//   };

//   onMounted(() => {
//     ipcRenderer.on("previewPageInit", (event, arg) => {
//       flag.value = true;
//     });
//     ipcRenderer.on("ChildWinClose", (event, arg) => {
//       flag.value = false;
//     });
//   });

//   watch(flag, () => {
//     if (flag.value) {
//       let obj = {
//         layout: JSON.stringify(currentItem.value.layouts),
//         configsJson: JSON.stringify(currentItem.value.configsJson),
//       };
//       ipcRenderer.send("infoToMain", obj);
//     }
//   });

//   return {
//     preview,
//   };
// };
